package com.ts.api.module.match.plan.internal.selection.base;

import com.gitee.apanlh.util.base.CollUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.ts.api.module.match.plan.internal.distribute.model.PlanDistributePhoneMaskField;
import com.ts.api.module.match.plan.internal.distribute.model.PlanDistributeResult;
import org.springframework.stereotype.Component;

import java.util.Comparator;
import java.util.List;

/**
 *  基础单价排序器
 *
 *  @author Pan
 */
@Component
public class BasePriceSort {

    /**
     *  根据手机号md5模式排序
     *
     *  @param  listSucMatchResult
     *  @return List
     */
    public List<PlanDistributeResult> sortByPhoneMd5(List<PlanDistributeResult> listSucMatchResult) {
        //  合并实体
        List<PlanDistributeResult> results = CollUtils.newArrayList();

        //  手机号md5-价格排序
        List<PlanDistributeResult> phoneMd5Results = CollUtils.find(listSucMatchResult, t -> ValidParam.isNotNull(t.getPlanDistributeField().getPhoneMd5Field()));
        if (ValidParam.isNotEmpty(phoneMd5Results)) {
            phoneMd5Results.sort(
                //  价格排序优先-倒序
                Comparator.comparing((PlanDistributeResult result) -> result.getPlanDistributeField().getPhoneMd5Field().getPrice(), Comparator.reverseOrder())
                //  本地机构优先-倒序
                .thenComparing((PlanDistributeResult result) -> result.getProductPlanPO().getPriorityLocalOrg(), Comparator.reverseOrder())
            );
            results.addAll(phoneMd5Results);
        }
        return results;
    }

    /**
     *  根据手机号掩码模式排序
     *
     *  @param  listSucMatchResult
     *  @return List
     */
    public List<PlanDistributeResult> sortByPhoneMask(List<PlanDistributeResult> listSucMatchResult) {
        //  合并实体
        List<PlanDistributeResult> results = CollUtils.newArrayList();

        //  手机号掩码模式-价格排序
        List<PlanDistributeResult> phoneMaskResults = CollUtils.find(listSucMatchResult, t -> ValidParam.isNotNull(t.getPlanDistributeField().getListPhoneMaskField()));
        if (ValidParam.isNotEmpty(phoneMaskResults)) {
            phoneMaskResults.sort(
                //  价格排序优先-倒序
                Comparator.comparing((PlanDistributeResult result) -> {
                    List<PlanDistributePhoneMaskField> listPhoneMaskField = result.getPlanDistributeField().getListPhoneMaskField();
                    PlanDistributePhoneMaskField first = listPhoneMaskField.getFirst();
                    return first.getPrice();
                }, Comparator.reverseOrder())
                //  本地机构优先-倒序
                .thenComparing((PlanDistributeResult result) -> result.getProductPlanPO().getPriorityLocalOrg(), Comparator.reverseOrder())
            );
            results.addAll(phoneMaskResults);
        }
        return results;
    }
}
